from django.shortcuts import render

# 导包
from django.http import JsonResponse
from rest_framework.parsers import JSONParser
from rest_framework.decorators import api_view
import random, string, base64
from django.core.cache import cache
from django.core.signing import Signer
from datetime import timedelta
#导入数据模型
from .models import User,Item
# 分页包
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
# Create your views here.

#判空
def is_empty(c):
    return c is None or str(c).strip()==''

#生成token
def createtoken(name):
    randomstr=''.join(random.choices(string.ascii_letters,k=8))
    token=Signer().sign(randomstr+name)
    cache.set(f'test_{name}',token,timeout=timedelta(minutes=10).total_seconds())
    return token

#鉴权
def checkout(request):
    reqtoken=request.META.get('HTTP_TOKEN')
    if reqtoken is None:
        return False,'XXXX'
    untoken=Signer().unsign(reqtoken)
    name=untoken[8:]
    cachetoken=cache.get(f'test_{name}')

    if cachetoken is None:
        return  False,'XXXXX'
    return True,name

#base64加密
def b64base(c):
    bc=bytes(c,encoding='utf-8')
    b64c=base64.b64encode(bc).decode('utf-8')
    return b64c


#注册
@api_view(['POST'])
def adduser(request):

    data=JSONParser().parse(request)
    username=data.get('username')
    password=data.get('password')

    if is_empty(username) or is_empty(password):
        return JsonResponse({
            'msg':'账号密码不能为空'
        },status=400)

    if User.objects.filter(username=username).exists():
        return JsonResponse({
            'msg': '用户已存在'
        }, status=409)

    #加密密码
    pwd=b64base(password)


    User(username=username,password=pwd).save()
    return JsonResponse({
        'msg': '添加成功'
    })

#登录
@api_view(['POST'])
def login(request):
    data=JSONParser().parse(request)

    username = data.get('username')
    password = data.get('password')

    if is_empty(username) or is_empty(password):
        return JsonResponse({
            'msg': '账号密码不能为空'
        }, status=400)
    try:
        obj=User.objects.get(username=username)
        b64pwd=b64base(password)
        if obj.password==b64pwd:
            token=createtoken(username)
            return JsonResponse({
                'msg': '登录成功',
                'token':token
            })
        else:
            return JsonResponse({
                'msg': '登录失败',
            },status=400)
    except Exception as e:
        return JsonResponse({
            'msg':'服务器内部错误'
        },status=500)


#发布商品
@api_view(['POST'])
def additem(request):

    data=JSONParser().parse(request)

    title=data.get('title')
    price=data.get('price')
    userid=data.get('userid')

    if is_empty(title) or is_empty(price):
        return JsonResponse({
            'msg': '必填项不能为空'
        }, status=400)
    try:
        Item(title=title,price=price,seller_id_id=userid).save()

        return JsonResponse({
            'msg':'发布成功'
        })
    except Exception as e:
        return JsonResponse({
            'msg': '发布失败'
        },status=400)



